package org.adream.account.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import org.adream.account.dao.SchoolBasicDao;
import org.adream.account.dao.SchoolDao;
import org.adream.account.entity.SchoolEntity;
import org.adream.account.util.SolrUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class SolrSearchService {

	private static final Logger logger = LoggerFactory.getLogger(SolrSearchService.class);
	
	@Autowired
	SolrUtils solrUtils;
	
	@Value("${solr.baseurl}")
	String solrBaseUrl;   //纯 URL
	
	@Value("${solr.schoolCore}")
	private String schoolCore;
	
	@Value("${solr.schoolBasicCore}")
	private String schoolBasicCore;
	
	@Value("${solr.user}")
	private String solrUser;
	
	@Value("${solr.pwd}")
	private String solrPwd;
	
	@Value("${env}")
	private String env;
	
	@Autowired
	SchoolDao schoolDao;
	
	@Autowired
	SchoolBasicDao schoolBasicDao;
	
	public SolrDocumentList solrSearch(String where) {
		SolrDocumentList results = null;
		try {
			results = solrUtils.query(where);
		} catch (SolrServerException e) {

		} catch (IOException e) {

		}
		return results;
	}
	/**
	 * 学校搜索
	 * @param where
	 * @return
	 */
	public SolrDocumentList schoolSearch(String where) {
		SolrDocumentList results = null;
		try {
			results = solrUtils.querySchool(where,null);
		} catch (SolrServerException e) {

		} catch (IOException e) {

		}
		return results;
	}
	
	public SolrDocumentList adreamCenterSearch(String where) {
		SolrDocumentList results = null;
		try {
			results = solrUtils.querySchool(where," AND id:SQ1000*");
		} catch (SolrServerException e) {

		} catch (IOException e) {

		}
		return results;
	}
	/**
	 * 搜索页面 高亮显示
	 * @param searchValue
	 * @param source
	 * @param time
	 * @param sort
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	public Map<String, Object> highlightSearch(String searchValue,String source,String time,String sort,Integer pageNo,Integer pageSize) {
		logger.info("查询结果集,并高亮显示");
		logger.info(source+":"+time+":"+sort);
		QueryResponse response = null;
		SolrDocumentList results = null;
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try {
			response = solrUtils.highlightSearch(searchValue,source,time,sort,pageNo,pageSize);
			// 获取结果集
			results = response.getResults();
			//查询结果数量
			resultMap.put("resultNumFound", response.getResults().getNumFound());
			Map<String, Map<String, List<String>>> highlighting = response.getHighlighting(); // 高亮查询的结果集
			Set<String> set = highlighting.keySet();
			for (String id : set) {
				Map<String, List<String>> map = highlighting.get(id); // id对应的查询结果，可能有多个字段，所以是map结构
				Set<String> set2 = map.keySet(); // 字段名集合
				// 遍历字段
				for (String field : set2) {
					List<String> list = map.get(field); // 字段对应的值，因为分词了，所以是一个String列表
					for (String s : list) {
						for (SolrDocument result : results) {
							if (id.equals((String) result.getFieldValue("id"))) {
								result.setField(field, s);
							}
						}
					}
				}
			}
		} catch (SolrServerException e) {
			logger.error("发生异常:" + e.getMessage());
		} catch (IOException e) {
			logger.error("io异常:" + e.getMessage());
		}
		resultMap.put("resultList", results);
		return resultMap;
	}
	
	
	public void timingTask() {
		Calendar todayStart = Calendar.getInstance();
		todayStart.setTime(new java.util.Date());
		todayStart.set(Calendar.HOUR_OF_DAY, 0);
		todayStart.set(Calendar.MINUTE, 20);
		todayStart.set(Calendar.SECOND, 0);
		todayStart.add(Calendar.DAY_OF_YEAR,0);
		java.util.Date todayStartDate = todayStart.getTime();
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				try {
					syncSchoolData();
				} catch (Exception e) {
					logger.error("学校数据同步出错1...");
				}
				try {
					syncSchoolBasicData();
				} catch (Exception e) {
					logger.error("学校数据同步出错2...");
				}
			}
		};
		Timer timer = new Timer();
		long intevalPeriod = 24 * 60 * 60 * 1000;
		timer.scheduleAtFixedRate(task, todayStartDate, intevalPeriod);
	}
	/**
	 *  同步school core
	 * @throws IOException
	 * @throws SolrServerException
	 */
	private void syncSchoolData() throws IOException, SolrServerException {
		if(!"pro".equals(env)) {
			logger.debug("非生产环境 不同步！");
			return;
		}
		
		HttpSolrClient httpSolrClient = new HttpSolrClient.Builder(solrBaseUrl).build();
		
		List<SchoolEntity> schoolList = schoolDao.querySchoolsByDr(1);
		if(schoolList.isEmpty()) {
			return;
		}
		List<SolrInputDocument> list = new ArrayList<SolrInputDocument>();
		for(SchoolEntity schoolEntity : schoolList) {
			SolrInputDocument inputDocument = new SolrInputDocument();
	        inputDocument.addField("id",schoolEntity.getSid());
	        inputDocument.addField("title",schoolEntity.getSname());
	        list.add(inputDocument);
		}
		
        UpdateRequest updateRequest = new UpdateRequest();
		updateRequest.add(list);
		updateRequest.setBasicAuthCredentials(solrUser,solrPwd);
		UpdateResponse updateResponse = updateRequest.commit(httpSolrClient, schoolCore);
		logger.debug("学校数据同步结束，状态码："+updateResponse.getStatus());
	}
	/**
	 *  同步 schoolBasic core
	 * @throws IOException
	 * @throws SolrServerException
	 */
	private void syncSchoolBasicData() throws IOException, SolrServerException {
		if(!"pro".equals(env)) {
			logger.debug("非生产环境 不同步！");
			return;
		}
		
		HttpSolrClient httpSolrClient = new HttpSolrClient.Builder(solrBaseUrl).build();
		
		List<Map<String,String>> schoolList = schoolBasicDao.queryInfo();
		if(schoolList.isEmpty()) {
			return;
		}
		List<SolrInputDocument> list = new ArrayList<SolrInputDocument>();
		for(Map<String,String> schoolEntity : schoolList) {
			SolrInputDocument inputDocument = new SolrInputDocument();
	        inputDocument.addField("id",schoolEntity.get("asid"));
	        inputDocument.addField("title",schoolEntity.get("sname"));
	        inputDocument.addField("roles",schoolEntity.get("roles"));
	        list.add(inputDocument);
		}
		
        UpdateRequest updateRequest = new UpdateRequest();
		updateRequest.add(list);
		updateRequest.setBasicAuthCredentials(solrUser,solrPwd);
		UpdateResponse updateResponse = updateRequest.commit(httpSolrClient, schoolBasicCore);
		logger.debug("(改 )学校数据同步结束，状态码："+updateResponse.getStatus());
	}
	public SolrDocumentList schoolBasicSearch(String where) {
		SolrDocumentList results = null;
		try {
			//如果需要添加条件角色条件  可以 添加 eg: --> AND roles: *1234*  <--
			results = solrUtils.schoolBasicSearch(where,null);
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return results;
	}	
}